<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function salesman_distributor_map_add_page($id) {
    $temp = drupal_get_form('salesman_distributor_map_edit_form',$id);
    return drupal_render($temp );
}

function salesman_distributor_map_edit_page($id) {
    $temp = drupal_get_form('salesman_distributor_map_edit_form', $id);
    return drupal_render($temp );
}

function salesman_distributor_map_edit_form($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) && !empty($form_state['build_info']['args'][0])? $form_state['build_info']['args'][0] : "";
    if (!empty($id)) {
        $record = salesman_distributor_map_load($id);
        if (empty($record)) {
            drupal_set_message(t('销售员零售商映射不存在！'), 'status', FALSE);
            drupal_goto('sales/salesman_distributor_map/list');
        }
        $form_state['update'] = true;
        $form_state['id'] = $id;
    }else{
        $form_state['insert'] = true;
    }

//     $form['salesman_wapper']['#markup']='销售员*';
    $form['employee_list']   =  _insert_loginuser_choose_salesman_selection($user,!empty($record)?$record->salesman_id:$user->uid,NULL,'add');
//    $form['address_distributor'] = get_all_distributors();
////        _insert_address_distributor_selection_form($form,$form_state,'address_distributor',!empty($record) ? $record->distributor_id : '','省,市,县必填');
//
    $form['distributor_name'] = _insert_distributor_select_info($form,$form_state,!empty($record)?$record->distributor_id:'');
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => '提交',
        '#access' => salesman_distributor_map_edit_form_submit_access($form_state, $id),
    );
    return $form;
}

function salesman_distributor_map_edit_form_validate($form, &$form_state) {
    $empty = false;
    if(empty($form_state['values']['employee_list'])){
        form_set_error('employee_list', '必须填写 销售员');
        $empty = true;
    }
    if(empty($form_state['values']['distributor_name'])){
        form_set_error('distributor_name', '必须填写 经销商');
        $empty = true;
    }


    $distributor_id = "";
    if(!$empty){
        $distributor_id = get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false);
        if(empty($distributor_id)){
            $empty = true;
            form_set_error('distributor_name', "经销商信息不存在！");
        }
    }
    if(!$empty && isset($form_state['insert']) && $form_state['insert']) {
        $query = db_select('salesman_distributor_map', 'sd');
        $query->condition('sd.distributor_id', $distributor_id);
        $query->condition('sd.salesman_id', $form_state['values']['employee_list']);
        $query->fields('sd');
        $record = $query->execute()->fetchAssoc();
        if (!empty($record)) {
            form_set_error('', "该销售员与该经销商已存在对应关系！");

        }
    }
    if(!$empty && isset($form_state['update']) && $form_state['update']) {
        $query = db_select('salesman_distributor_map', 'sd');
        $query->condition('sd.distributor_id', $distributor_id);
        $query->condition('sd.salesman_id', $form_state['values']['employee_list']);
        $query->condition('sd.map_id',$form_state['id'],'!=');
        $query->fields('sd');
        $record = $query->execute()->fetchAssoc();
        if (!empty($record)) {
            form_set_error('', "该销售员与该经销商已存在对应关系！");

        }
    }
}

function salesman_distributor_map_edit_form_submit($form, &$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) &&!empty($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : "";
    if (arg(2) == 'add') { //add new salesman_distributor_map
        $nid = db_insert('salesman_distributor_map') // Table name no longer needs {}
        ->fields(array(
            'salesman_id' => $form_state['values']['employee_list'],
            'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('添加成功！'), 'status', FALSE);
        }
       drupal_goto('sales/salesman_distributor_map/add/'.$nid);
    } else {
        $nid = db_update('salesman_distributor_map') // edit exsting store. todo: update only modified fields
        ->fields(array(
            'salesman_id' => $form_state['values']['employee_list'],
            'distributor_id' => get_id_from_string_field('distributor','distributor_id','distributor_name',$form_state['values']['distributor_name'],false),
            'author_uid' => $user->uid,
            'timestamp' => time(),))
            -> condition('map_id',$id, '=')
            ->execute();
        if ($nid > 0) {
            drupal_set_message(t('修改成功！'), 'status', FALSE);
        }
//        drupal_goto('sales/salesman_distributor_map/list');
    }
}

function salesman_distributor_map_edit_form_submit_access(&$form_state) {
    global $user;
    $id = isset($form_state['build_info']['args'][0]) &&!empty($form_state['build_info']['args'][0]) ? $form_state['build_info']['args'][0] : "";
    if (!empty($id)) {
        //edit
        $salesman_distributor_map = salesman_distributor_map_load($id);
        if ($salesman_distributor_map) {
            $user_info = _get_user_info($user->uid);
            if ($salesman_distributor_map->author_uid == $user->uid|| $user_info['role'] === 'administrator') {
                return TRUE;
            } else {
                return FALSE;
            }
        } else {
            //load false
            drupal_set_message(t('销售员零售商映射不存在！'), 'status', FALSE);
            return FALSE;
        }
    } else {
        //add
        return user_access('manage salesman');
    }
}

function salesman_distributor_map_load($id) {
    $result = db_select('salesman_distributor_map', 'P')
        -> fields('P')
        -> condition('P.map_id',$id, '=')
        -> execute()
        -> fetchObject();
    return $result;
}
